<template>
    <div class="p-2">
        <searchrevealing>
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="88px">
                <el-form-item label="出库类型" prop="outStockType">
                    <el-select v-model="queryParams.outStockType" placeholder="请选择出库类型" clearable style="width: 220px"
                        filterable @change="onChange">
                        <el-option v-for="dict in ReasonstorageList" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出库部门" prop="outDeptId"
                    v-if="queryParams.outStockType == '1' || queryParams.outStockType == '3'">
                    <el-select style="width: 220px" v-model="queryParams.outDeptId" placeholder="请选择" clearable
                        filterable>
                        <el-option v-for="dict in returnList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>

                <el-form-item label="产品部门" prop="stockDeptId">
                    <el-select v-model="queryParams.stockDeptId" placeholder="请选择产品部门" clearable
                        @change="warehouseChange" filterable style="width: 220px">
                        <el-option v-for="dict in warehousedepList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出库员" prop="stockUserId">
                    <el-select v-model="queryParams.stockUserId" placeholder="请选择出库员" clearable filterable
                        style="width: 220px">
                        <el-option v-for="dict in stockUserList" :key="dict.userId" :label="dict.nickName"
                            :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出库单状态" prop="cancelStatus">
                    <el-select v-model="queryParams.cancelStatus" placeholder="请选择出库单状态" clearable style="width: 220px">
                        <el-option v-for="dict in cancelStatusList" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出库时间" prop="outTimeArray">
                    <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.outTimeArray" type="daterange"
                        range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                        style="width: 220px" />
                </el-form-item>
                <el-form-item label="商品名称" prop="styleName">
                    <el-input v-model="queryParams.styleName" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="类目" prop="categoryIdList">
                    <el-cascader v-model="queryParams.categoryIdList" :options="options" style="width: 220px" clearable
                        collapse-tags filterable ref="categoryRef" @change="handleChange" placeholder="请选择"
                        :props="props" />
                </el-form-item>
                <el-form-item label="库存编码" prop="stockCode">
                    <el-input v-model="queryParams.stockCode" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="出库单号" prop="outId">
                    <el-input v-model="queryParams.outId" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="69/商品编码" prop="codeContent">
                    <el-input v-model="queryParams.codeContent" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
            </el-form>
            <div class="form_button">
                <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
            </div>
        </searchrevealing>
        <el-card shadow="never">
            <template #header>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'产品部出库记录出库详单'"
                    @updateColumn="getColmun"></right-toolbar>
            </template>
            <el-table v-loading="loading" :data="selectionRecordList" border @header-dragend="dragEnd">
                <el-table-column label="序号" type="index" width="55" align="center" :fixed="true" />
                <el-table-column v-for="(item, index) in storageRecordColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <span v-if="item.prop == 'cancelStatus'">{{ scope.row.cancelStatus == 1 ? '作废' :'正常' }}</span>
                        <span v-if="item.prop == 'outNum'">{{ scope.row.cancelStatus == 1 ? '-' : scope.row.outNum }}</span>
                        <span v-if="item.prop == 'stockNum'">{{ scope.row.cancelStatus == 1 ? '-' : scope.row.stockNum }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" :leftText="statisticsText" />
        </el-card>
    </div>
</template>



<script setup name="StorageRecord" lang="ts">
import { OutBoundQueryParmas, OutBoundVO } from '@/api/group/productOutbound/types'
import { selectOutDetailed, getStickDept, getUserLists, getCategoryLists } from '@/api/group/productOutbound/index'
import { loginDeptList, getOutDepByName, getUserById } from '@/api/group/qualityControl'
import { loginSupplierList } from '@/api/group/supplier/index'
import { listColumn } from '@/api/system/column';
const { proxy } = getCurrentInstance() as any;
const storageRecordColumns = ref()
const selectionRecordList = ref<OutBoundVO[]>([]);
const loading = ref(true);
const total = ref(0);
const statisticsText = ref('')
const showSearch = ref(true);
const queryFormRef = ref<ElFormInstance>();

const returnList = ref<{ deptId: string; deptName: string; }[]>([])

const queryLoading = ref(false)
const columnData = ref()
const ReasonstorageList = reactive([
    { label: '主播选品', value: '1' },
    { label: '供应商', value: '2' },
    { label: '品控审核', value: '3' },
    { label: '借调出库', value: '4' },
])
// 入库部门
const warehousedepList = ref<{ deptName: string; deptId: string }[]>([])
// 入库员
const stockUserList = ref<{ nickName: string; userId: string }[]>([])

const queryParams = ref<OutBoundQueryParmas>({
    pageNum: 1,
    pageSize: 10,
    outStockType: undefined,
    stockDeptId: undefined,
    stockUserId: undefined,
    outId: undefined,

    styleName: undefined,
    stockCode: undefined,
    outDeptId: undefined,
    outTimeArray: [],
    outStartTime: '',
    outEndTime: '',
    categoryIdList: [],
    codeContent: '',
    cancelStatus: undefined
})
const categoryRef = ref();
const options = ref()
const props = {
    multiple: true
}
// 出库单状态
const cancelStatusList = ref([
    { label: '正常', value: '0', },
    { label: '作废', value: '1', }
])
/**
 * 出库类型筛选
 */
const onChange = () => {
    queryParams.value.outDeptId = undefined
    // 主播选品
    if (queryParams.value.outStockType == '1') {
        getreturnList('运营部门');
        // 品控审核
    } else if (queryParams.value.outStockType == '3') {
        getreturnList('审核部门');
    }
}
/**
 * 获取还品出库主播列表
 */
const getreturnList = async (deptName: string) => {
    const res = await getOutDepByName({ deptName: deptName })
    returnList.value = res.data
}
/** 获取类目 */
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {

}
/** 根据入库部门查询入库员 */
const warehouseChange = async (event: string) => {
    if (event) {
        const res = await getUserLists({ deptId: event })
        stockUserList.value = res.data
        queryParams.value.stockUserId = undefined
    } else {
        stockUserList.value = []
        queryParams.value.stockUserId = undefined
    }
}
/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        if (queryParams.value.outTimeArray && queryParams.value.outTimeArray.length) {
            queryParams.value.outStartTime = queryParams.value.outTimeArray[0]
            queryParams.value.outEndTime = queryParams.value.outTimeArray[1]
        } else {
            queryParams.value.outStartTime = ''
            queryParams.value.outEndTime = ''
        }
        const res = await selectOutDetailed(queryParams.value);
        selectionRecordList.value = res.rows;
        total.value = res.total;
        loading.value = false;
        statisticsText.value = res.msg
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    stockUserList.value = []
    handleQuery();
};
/** 获取入库部门 */
const getWarehousingDept = async () => {
    const res = await getStickDept()
    warehousedepList.value = res.data
}
/** 导出按钮操作 */
const handleExport = () => {
    proxy?.downloadAsync("basic/stock/getOutDetailedExport", {
        ...queryParams.value,
    }, `出库详单_${new Date().getTime()}.xlsx`)
}
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('产品部出库记录出库详单')
    storageRecordColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
onMounted(async () => {
    queryParams.value.pageNum = 1;
    await getColmun();
    await getList();
    getWarehousingDept();
    getCategoryList();
})

</script>
<style lang="scss" scoped>
.mb96 {
    margin-bottom: 96px;
}

:deep(.el-card__header) {
    display: flex;
    justify-content: flex-end;
}

.form_button {
    display: flex;
    justify-content: flex-end;
}
</style>